package cn.myapps.msg.service.impl;

import cn.myapps.msg.mail.entity.MailAccount;
import cn.myapps.msg.mail.service.IMailAccountService;
import cn.myapps.msg.vo.MailFile;
import cn.myapps.msg.service.IMailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.UrlResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

@Slf4j
@Service
public class MailServiceImpl implements IMailService {

    @Autowired
    IMailAccountService mailAccountService;

    @Override
    public void sendSimpleMail(String fromMail, String toMail, String subject, String content) {
        if (!StringUtils.isBlank(toMail)) {
            JavaMailSender sender = getSender(fromMail);

            String[] toMails = toMail.split(";");

            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(fromMail);
            simpleMailMessage.setTo(toMails);
            simpleMailMessage.setSubject(subject);
            simpleMailMessage.setText(content);

            try {
                sender.send(simpleMailMessage);
                log.info("发送给" + toMail + "的邮件已经发送成功");
            } catch (Exception e) {
                log.error("发送给" + toMail + "的邮件时发生异常", e);
            }
        }
    }

    @Override
    public void sendHtmlMail(String fromMail, String toMail, String subject, String content) {
        JavaMailSender sender = getSender(fromMail);

        MimeMessage mimeMessage = sender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            if (!StringUtils.isBlank(toMail)) {
                String[] toMails = toMail.split(";");
                mimeMessageHelper.setTo(toMails);
            }
            mimeMessageHelper.setFrom(fromMail);
            mimeMessageHelper.setText(content, true);
            mimeMessageHelper.setSubject(subject);

            sender.send(mimeMessage);
            log.info("发送给" + toMail + "的html邮件已经发送。 subject：" + subject);
        } catch (MessagingException e) {
            log.error("发送给" + toMail + "的html发送异常。subject：" + subject);
        }
    }


    @Override
    public void sendAttachmentsMail(String fromMail, String toMail, String subject, String content, String filePath) {
        try {
            JavaMailSender sender = getSender(fromMail);
            MimeMessage message = sender.createMimeMessage();

            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(fromMail);
            if (!StringUtils.isBlank(toMail)) {
                String[] toMails = toMail.split(";");
                helper.setTo(toMails);
            }
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf("/"));
            helper.addAttachment(fileName, file);

            sender.send(message);
            log.info("发送给" + toMail + "带附件的邮件已经发送成功");
        } catch (MessagingException e) {
            log.error("发送给" + toMail + "带附件的邮件时发生异常", e);
        }
    }

    /**
     *
     * @param toMail
     * @param subject
     * @param content
     * @param mailFiles 邮件文件
     *
     */
    @Override
    public void sendUriAttachmentsMail(String fromMail, String toMail, String subject, String content, List<MailFile> mailFiles) {

        if (!StringUtils.isBlank(toMail)) {
            JavaMailSender sender = getSender(fromMail);
            MimeMessage message = sender.createMimeMessage();
            String[] toMails = toMail.split(";");

            for (String toMailOne : toMails) {
                try {
                    MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
                    helper.setFrom(fromMail);
                    helper.setTo(toMailOne);
                    helper.setSubject(subject);
                    helper.setText(content, true);

                    // 添加邮件附件
                    for (MailFile mailFile : mailFiles) {
                        if (StringUtils.isNotBlank(mailFile.getFileURI())) {
                            // ByteArrayResource resource = new ByteArrayResource(readInputStream(new URL(mailFile.getFileURI()).openStream()));
                            UrlResource resource = new UrlResource(mailFile.getFileURI());
                            helper.addAttachment(mailFile.getFileName(), resource);
                        }
                    }

                    sender.send(message);
                    log.info("发送给" + toMail + "带Oss附件的邮件已经发送成功");
                } catch (MessagingException e) {
                    log.error("发送给" + toMail + "带Oss附件的邮件时发生异常", e);
                    throw new RuntimeException("邮件发送异常");
                } catch (IOException e) {
                    log.error("发送给" + toMail + "带Oss附件的邮件时发生IO异常", e);
                    throw new RuntimeException("邮件发送异常");
                }
            }
        }
    }

    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    private JavaMailSender getSender(String fromMail) {
        MailAccount mailAccount = mailAccountService.findByMsgFrom(fromMail);

        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(mailAccount.getHost());
        sender.setPort(mailAccount.getPort());
        sender.setProtocol("smtps");
        sender.setUsername(mailAccount.getUser());
        sender.setPassword(mailAccount.getPass());

        Properties props = new Properties();
        props.setProperty("mail.smtp.auth", mailAccount.getAuth()+"");
        props.setProperty("mail.starttls.enable", mailAccount.getStartttlsEnable()+"");
        props.setProperty("mail.ssl.enable", mailAccount.getSslEnable()+"");

        sender.setJavaMailProperties(props);

        return sender;
    }
}
